//
//  JPersonageController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/20.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JPersonageController.h"
#import <WebKit/WebKit.h>

@interface JPersonageController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>

@property (nonatomic,strong) WKWebView *webView;


@end

@implementation JPersonageController

#pragma mark----- VC 生命周期-----

//-(void)viewWillDisappear:(BOOL)animated{
//    [super viewWillDisappear:animated];
    //移除监听
//    [self.webView removeObserver:self forKeyPath:@"loading"];
//    [self.webView removeObserver:self forKeyPath:@"title"];
//    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
//}

//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:YES];
//    
//    //添加KVO监听
//    [self.webView addObserver:self
//                   forKeyPath:@"loading"
//                      options:NSKeyValueObservingOptionNew
//                      context:nil];
//    [self.webView addObserver:self
//                   forKeyPath:@"title"
//                      options:NSKeyValueObservingOptionNew
//                      context:nil];
//    [self.webView addObserver:self
//                   forKeyPath:@"estimatedProgress"
//                      options:NSKeyValueObservingOptionNew
//                      context:nil];
//    
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    [super InitUI];
//    self.navigationView.hidden = YES;
//    self.contentView.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatWebView];
}

//创建webView
- (void)creatWebView{
    
    WKWebViewConfiguration *config = [WKWebViewConfiguration new];
    //初始化偏好设置属性：preferences
    config.preferences = [WKPreferences new];
    //The minimum font size in points default is 0;
    config.preferences.minimumFontSize = 10;
    //是否支持JavaScript
    config.preferences.javaScriptEnabled = YES;
    //不通过用户交互，是否可以打开窗口
    config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    //通过JS与webView内容交互
    config.userContentController = [WKUserContentController new];
    // 注入JS对象名称senderModel，当JS通过senderModel来调用时，我们可以在WKScriptMessageHandler代理中接收到
    [config.userContentController addScriptMessageHandler:self name:html_name];
    
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 20, kWindowW, kWindowH-20) configuration:config];
//    NSURL *path = [[NSBundle mainBundle] URLForResource:@"WKWebViewText" withExtension:@"html"];
    
    NSDictionary *dic = @{@"ConcernId":@([GLOBALDATA userInfoModel].CustomerId),
                          @"CustomerId":@([GLOBALDATA userInfoModel].CustomerId),
                          @"Name":@"",
                          @"UserId":@([GLOBALDATA userInfoModel].CustomerId),
                          @"page":@(1),
                          @"pageSize":@(10)};
    
//    ConcernId:"10004"CustomerId:"10004"Name:""UserId:"10004"page:1pageSize:10
    
    NSString * jsonParam = [self convertToJsonData:dic];
//    NSString * jsonParam =[NSString stringWithFormat:@"{\"paramJson\":{\"page\":\"1\",\"user_id\":\"%@\"}}",@"101020"];
    NSMutableURLRequest * requestShare = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:prosonageHTML_URL_STR]];
    
    
    [requestShare setHTTPMethod: @"POST"];
    [requestShare setHTTPBody: [jsonParam dataUsingEncoding: NSUTF8StringEncoding]];
    [self.webView loadRequest:requestShare];
    
    [self.view addSubview:self.webView];
    
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
}


//#pragma mark - KVO监听函数
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
//    if ([keyPath isEqualToString:@"title"]) {
//        self.title = self.webView.title;
//    }else if([keyPath isEqualToString:@"loading"]){
//        [SVProgressHUD show];
//    }
//    else if ([keyPath isEqualToString:@"estimatedProgress"]){
//        
//    }
//    
//    if (!self.webView.loading) {
//        [UIView animateWithDuration:0.5 animations:^{
//        }];
//    }
//    
//}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    //这里可以通过name处理多组交互
    if ([message.name isEqualToString:html_name]) {
        //body只支持NSNumber, NSString, NSDate, NSArray,NSDictionary 和 NSNull类型
//        NSLog(@"================%@",message.body);
        if ([message.body isKindOfClass:[NSString class]]) {
            if ([message.body isEqualToString:goback_beautiful]) {
                
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
        
    }
    
}

#pragma mark = WKNavigationDelegate
//在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *hostname = navigationAction.request.URL.host.lowercaseString;
    NSLog(@"hostname====%@",hostname);
    if (navigationAction.navigationType == WKNavigationTypeLinkActivated
        && ![hostname containsString:@".touhanggo.com"]) {
        // 对于跨域，需要手动跳转
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        
        // 不允许web内跳转
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
}
//在响应完成时，调用的方法。如果设置为不允许响应，web内容就不会传过来
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
//    decisionHandler(WKNavigationResponsePolicyAllow);
//    
//    
//    
//}
////接收到服务器跳转请求之后调用
//- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
//    
//}
//
//开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [SVProgressHUD show];
}
////当内容开始返回时调用
//- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
//    
//}
//页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//    NSLog(@"title:%@",webView.title);
    [SVProgressHUD dismiss];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [SVProgressHUD showErrorWithStatus:@"加载失败"];
}

//#pragma mark WKUIDelegate
//
////alert 警告框
//- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"调用alert提示框" preferredStyle:UIAlertControllerStyleAlert];
//    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler();
//    }]];
//    [self presentViewController:alert animated:YES completion:nil];
//    NSLog(@"alert message:%@",message);
//    
//}
//
////confirm 确认框
//- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认框" message:@"调用confirm提示框" preferredStyle:UIAlertControllerStyleAlert];
//    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler(YES);
//    }]];
//    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler(NO);
//    }]];
//    [self presentViewController:alert animated:YES completion:NULL];
//    
//    NSLog(@"confirm message:%@", message);
//    
//}
//
//- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"输入框" message:@"调用输入框" preferredStyle:UIAlertControllerStyleAlert];
//    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
//        textField.textColor = [UIColor blackColor];
//    }];
//    
//    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler([[alert.textFields lastObject] text]);
//    }]];
//    
//    [self presentViewController:alert animated:YES completion:NULL];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (void)leftButtonClick:(UIButton *)leftButton
//{
//    if ([self.webView canGoBack]) {
//        [self.webView goBack];
//        NSLog(@"back");
//    }
//}

// 字典转json字符串方法

-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
